﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MCCA.Cache
{
    public static class CacheManager
    {

        #region [           Members           ]

        private static object syncObj = new object();
        private static Hashtable ht = new Hashtable();

        static ICacheEngine cacheEngine = null;

        #endregion

        #region [           Methods           ]

        public static void SetEngine(ICacheEngine engine)
        {
            if (engine == null)
                throw new ArgumentNullException("CacheEngine cannot be null.");

            if (cacheEngine != null)
                throw new ArgumentNullException("CacheEngine has already been setted.");

            lock (syncObj)
            {
                if (cacheEngine == null)
                    cacheEngine = engine;
            }
        }

        public static CacheEntityTable<K, V> GetCacheEntityTable<K, V>(string cacheKey)
        {
            return GetCacheEntityTable<K, V>(cacheKey, 0);
        }

        public static CacheEntityTable<K, V> GetCacheEntityTable<K, V>(string cacheKey, int cacheDuration)
        {
            if (cacheEngine == null)
                throw new ArgumentNullException("CacheEngine haven't been setted.");

            CacheEntityTable<K, V> table = null;

            if (!ht.ContainsKey(cacheKey))
            {
                lock (syncObj)
                {
                    if (!ht.ContainsKey(cacheKey))
                    {
                        table = new CacheEntityTable<K, V>(cacheKey, cacheEngine, cacheDuration);
                        ht[cacheKey] = table;
                    }
                }
            }

            table = ht[cacheKey] as CacheEntityTable<K, V>;

            return table;
        }

        #endregion
    }
}
